﻿// <copyright file="CommunityCommentsByDate.cs" company="Microsoft Corporation">
// Copyright (c) 2009 Microsoft Corporation All Rights Reserved
// </copyright>
// <author>Michael S. Scherotter</author>
// <email>mischero@microsoft.com</email>
// <date>2009-04-13</date>
// <summary>CommunityCommentsByDate Silverlight CLR class definition</summary>

namespace NYTimes
{
    using System;
    using System.ComponentModel;
    using System.Globalization;
    using System.Text;
    using NYTimes.Core;
    using Synergist;

    /// <summary>
    /// New York Times Community Comments by Date API
    /// </summary>
    /// <remarks>
    /// <list type="table">
    /// <listheader>
    /// <term>Application Resource Key</term>
    /// <description>Key to add to application resources</description>
    /// </listheader>
    /// <item>
    /// <term>
    /// NYTCommunityKey
    /// </term>
    /// <description>Community API Key</description>
    /// </item>
    /// <item>
    /// <term>
    /// NYTCommunityQPS
    /// </term>
    /// <description>Rate Limiting (default 30 QPS)</description>
    /// </item>
    /// </list>
    /// </remarks>
    /// <example>
    /// This is from the DemoNYTimes sample CommunityCommentsByDatePage.xaml
    /// <code>
    /// <![CDATA[
    /// <UserControl x:Class="DemoNYTimes.CommunityCommentsByDatePage"
    ///    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    ///    xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
    ///    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    ///    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    ///    xmlns:nyt="clr-namespace:NYTimes;assembly=NYTimesSilverlightKit" 
    ///    xmlns:nytvc="clr-namespace:NYTimes.ValueConverters;assembly=NYTimesSilverlightKit"
    ///    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    ///    d:DesignWidth="640" d:DesignHeight="480" mc:Ignorable="d">
    ///    <UserControl.Resources>
    ///        <nyt:CommunityCommentsByDate x:Key="CommentsByDateDS" d:IsDataSource="True"/>
    ///        <nytvc:FrameworkElementTagToCommentSortTypeConverter x:Key="CommentSortTypeConverter"/>
    ///    </UserControl.Resources>
    ///    <Grid x:Name="LayoutRoot" Background="White">
    ///        <Grid.RowDefinitions>
    ///            <RowDefinition Height="Auto"/>
    ///            <RowDefinition/>
    ///        </Grid.RowDefinitions>
    ///        <StackPanel Orientation="Horizontal">
    ///            <basics:DatePicker 
    ///                SelectedDate="{Binding Mode=TwoWay, Path=Date, Source={StaticResource CommentsByDateDS}}" 
    ///                Height="Auto" VerticalAlignment="Stretch" Margin="2,2,2,2"/>
    ///            <TextBlock Text="Results:" TextWrapping="Wrap" VerticalAlignment="Center" 
    ///                Margin="2,2,2,2"/>
    ///            <TextBlock 
    ///                Text="{Binding Mode=OneWay, Path=Results.Count, Source={StaticResource CommentsByDateDS}}" 
    ///                TextWrapping="Wrap" VerticalAlignment="Center" Margin="2,2,2,2"/>
    ///            <TextBlock Text="Sort By:" TextWrapping="NoWrap" VerticalAlignment="Center" 
    ///            Margin="2,2,2,2"/>
    ///            <ComboBox Margin="2,2,2,2" 
    ///                SelectedItem="{Binding Sort, Mode=TwoWay, Source={StaticResource CommentsByDateDS}, Converter={StaticResource CommentSortTypeConverter}}">
    ///                <ComboBoxItem Content="Newest" Tag="Newest"/>
    ///                <ComboBoxItem Content="Oldest" Tag="Oldest"/>
    ///                <ComboBoxItem Content="Recommended" Tag="Recommended"/>
    ///                <ComboBoxItem Content="Replied" Tag="Replied"/>
    ///                <ComboBoxItem Content="Editors' Selection" Tag="EditorsSelection"/>
    ///            </ComboBox>
    ///        </StackPanel>
    ///        <ListBox Height="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
    ///            Width="Auto" Grid.Row="1" 
    ///            ItemsSource="{Binding Results, Source={StaticResource CommentsByDateDS}}" 
    ///            ItemTemplate="{StaticResource CommentTemplate}" 
    ///            ScrollViewer.HorizontalScrollBarVisibility="Disabled"/>
    ///    </Grid>
    /// </UserControl>
    /// ]]>
    /// </code>
    /// </example>
    public class CommunityCommentsByDate : CommunityBase
    {
        #region Fields
        /// <summary>
        /// the result offset
        /// </summary>
        private int offset;

        /// <summary>
        /// the date to search
        /// </summary>
        private DateTime date;

        /// <summary>
        /// The sort order
        /// </summary>
        private CommentSortType sort;

        #endregion

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the CommunityCommentsByDate class.
        /// </summary>
        public CommunityCommentsByDate()
        {
            this.Date = DateTime.Now;

            this.MaxResults = 25;

            if (SampleData.IsInDesignTool)
            {
                var xml = SampleData.GetSampleData("CommunityCommentsByDate.xml");

                this.ParseXml(xml);
            }
        }

        #endregion

        #region Properties
        /// <summary>
        /// Gets or sets the date to get comments for
        /// </summary>
        [Description("Gets or sets the date to get comments for"),
        TypeConverter(typeof(DateTimeTypeConverter))]
        public DateTime Date 
        { 
            get
            {
                return this.date;
            } 

            set
            {
                this.date = value;

                this.Offset = 0;
            } 
        }

        /// <summary>
        /// Gets or sets the sort order for the results.
        /// </summary>
        [Description("Gets or sets the sort order for the results.")]
        public CommentSortType Sort
        {
            get
            {
                return this.sort;
            }

            set
            {
                if (this.sort != value)
                {
                    this.sort = value;

                    this.Offset = 0;
                }
            }
        }

        /// <summary>
        /// Gets or sets the maximum results
        /// </summary>
        [Description("The maximum number of results to get.")]
        public int MaxResults { get; set; }

        /// <summary>
        /// Gets the offset
        /// </summary>
        public int Offset
        {
            get
            {
                return this.offset;
            }

            private set
            {
                this.offset = value;

                this.FetchResults(this.offset == 0);
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Generate a URI for the service
        /// </summary>
        /// <returns>the output URI string</returns>
        public override string GenerateUriFragment()
        {
            var builder = new StringBuilder();

            if (this.Date == DateTime.MinValue)
            {
                return null;
            }

            builder.AppendFormat(CultureInfo.InvariantCulture, "by-date/{0:yyyyMMdd}.xml?", this.Date);

            AppendSortType(builder, this.Sort);

            if (this.Offset > 0)
            {
                builder.AppendFormat(CultureInfo.InvariantCulture, "&offset={0}", this.Offset);
            }

            return builder.ToString();
        }

        /// <summary>
        /// Fetch the next set
        /// </summary>
        /// <returns>true if done, false if next batch should be returned</returns>
        public override bool FetchNextSet()
        {
            if (this.Results.Count < this.MaxResults && this.Results.Count < this.TotalComments)
            {
                this.Offset += 25;

                return false;
            }

            return true;
        }

        #endregion
    }
}
